package ru.efimmatytsin.tweeterella.services.impl;

import org.springframework.stereotype.Repository;
import ru.efimmatytsin.tweeterella.entities.Tweet;
import ru.efimmatytsin.tweeterella.entities.User;
import ru.efimmatytsin.tweeterella.services.TweetService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

/**
 * Created by Efim Matytsin on 17.02.15.
 */
@Repository
public class TweetServiceImpl implements TweetService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Tweet getTweet(BigInteger id) {
        Tweet result = null;
        if(entityManager.isOpen()){
            result = entityManager.find(Tweet.class,id);
        }
        return result;
    }

    @Override
    public Tweet saveTweet(Tweet tweet) {
        entityManager.persist(tweet);
        return tweet;
    }

    @Override
    public List<Tweet> getAllTweets() {
        Query query = entityManager.createQuery("SELECT e FROM Tweet e");
        return (List<Tweet>) query.getResultList();
    }

    @Override
    public List<Tweet> getUserTweets(User user) {
        Query query = entityManager.createQuery("SELECT e FROM Tweet e where e.fromUser = :user");
        query.setParameter("user",user);
        return (List<Tweet>) query.getResultList();
    }
}
